package com.cuitrip.business.user;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;
import com.lab.widget.WordCountView;

import java.util.HashMap;
import java.util.Map;

public class EditInfoDetailActivity extends CustomUiFragmentActivity {
    public static final String KEY_PLACE_HOLDER = "KEY_PLACE_HOLDER";
    public static final String KEY_TIP = "KEY_TIP";
    public static final String KEY_REQUEST_CODE = "REQUEST_CODE";
    public static final String KEY_VALUE = "KEY_VALUE";
    public static final String KEY_DIALOG_TITLE = "KEY_DIALOG_TITLE";
    public static final String KEY_DIALOG_CONTENT = "KEY_DIALOG_CONTENT";
    public static final String KEY_VALUE_MAX_LENGTH = "KEY_VALUE_MAX_LENGTH";
    public static final String KEY_SELECTED_VALUES = "KEY_SELECTED_VALUES";
    public static final String KEY_SELECT_ARRAY = "KEY_SELECT_ARRAY";
    public static final String KEY_SHOW_DIALOG = "KEY_SHOW_DIALOG";
    public static final String KEY_TITLE = "KEY_TITLE";

    private ApiProxy apiProxy;
    private int requestCode;
    private String placeHolder;
    private String value;
    private String tip;
    private int maxLength;
    private String dialogTitle;
    private String dialogContent;
    private String title;
    private boolean showDialog;
    private EditText editMInput1;
    private WordCountView editMInput2;
    private TextView textMInput1;
    private String[] selectedValues;
    private String[] selectArray;

    private IProxyCallback callBackModifyUserinfo = new ApiProxyCallBack<CtUserInfo>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(CtUserInfo data, CtApiResponse response) {
            LoginInstance.updateProfile(AppCoreRuntime.context, data, false);
            finish();
            ToastUtil.toast(R.string.feedback_edit_suc);
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            return super.onFaild(response);
        }
    };

    public static void startActivityWithShowDialig(
            Activity activity, String value, int maxLength,
            String holder, String dialogTitle, String dialogContent, String tip, int requestCode) {
        Intent intent = new Intent(activity, EditInfoDetailActivity.class);
        intent.putExtra(KEY_VALUE, value);
        intent.putExtra(KEY_VALUE_MAX_LENGTH, maxLength);
        intent.putExtra(KEY_PLACE_HOLDER, holder);
        intent.putExtra(KEY_TITLE, dialogTitle);
        intent.putExtra(KEY_DIALOG_TITLE, dialogTitle);
        intent.putExtra(KEY_DIALOG_CONTENT, dialogContent);
        intent.putExtra(KEY_REQUEST_CODE, requestCode);
        intent.putExtra(KEY_SHOW_DIALOG, true);
        intent.putExtra(KEY_TIP, tip);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startActivityWithoutShowDialig(
            Activity activity, String title, String value, int maxLength,
            String holder, String tip, int requestCode) {
        Intent intent = new Intent(activity, EditInfoDetailActivity.class);
        intent.putExtra(KEY_VALUE, value);
        intent.putExtra(KEY_TITLE, title);
        intent.putExtra(KEY_VALUE_MAX_LENGTH, maxLength);
        intent.putExtra(KEY_PLACE_HOLDER, holder);
        intent.putExtra(KEY_REQUEST_CODE, requestCode);
        intent.putExtra(KEY_SHOW_DIALOG, false);
        intent.putExtra(KEY_TIP, tip);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        Intent intent = getIntent();
        if (intent == null) {
            return null;
        }
        requestCode = intent.getIntExtra(EditSelfInfoActivity.KEY_REQUEST_CODE, -1);
        if (requestCode == -1) {
            return null;
        }
        initData(intent);

        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = title;
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarRightAreaName = getString(R.string.operation_ok_1);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_edit_info_detail);
        editMInput1 = (EditText) findViewById(R.id.editMInput1);
        editMInput2 = (WordCountView) findViewById(R.id.editMInput2);
        textMInput1 = (TextView) findViewById(R.id.textMInput1);
        apiProxy = ApiProxyBuilder.getBuilder()
                .addApiCallBack(ApiManager.MODIFY_USERINFO, callBackModifyUserinfo)
                .build();
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        requestCode = intent.getIntExtra(EditSelfInfoActivity.KEY_REQUEST_CODE, -1);
        if (requestCode == -1) {
            return;
        }
        initData(intent);
        int type = (requestCode & 0x0f0) >> 4;
        switch (type) {
            case 1:
                doMInput1();
                break;
            case 2:
                doMInput2();
                break;
        }
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public void onTopbarRightPress() {
        saveInfo();
    }

    private void initData(Intent intent) {
        dialogTitle = intent.getStringExtra(KEY_DIALOG_TITLE);
        title = intent.getStringExtra(KEY_TITLE);
        dialogContent = intent.getStringExtra(KEY_DIALOG_CONTENT);
        placeHolder = intent.getStringExtra(KEY_PLACE_HOLDER);
        maxLength = intent.getIntExtra(KEY_VALUE_MAX_LENGTH, Integer.MAX_VALUE);
        selectedValues = intent.getStringArrayExtra(KEY_SELECTED_VALUES);
        selectArray = intent.getStringArrayExtra(KEY_SELECT_ARRAY);
        value = intent.getStringExtra(KEY_VALUE);
        tip = intent.getStringExtra(KEY_TIP);
        showDialog = intent.getBooleanExtra(KEY_SHOW_DIALOG, false);
    }

    private void doMInput1() {
        setTitle(dialogTitle);
        View layoutMInput1 = findViewById(R.id.layoutMInput1);
        layoutMInput1.setVisibility(View.VISIBLE);
        editMInput1.setHint(placeHolder);
        editMInput1.setText(value);
        textMInput1.setText(tip);
    }

    private void doMInput2() {
        setTitle(dialogTitle);
        View layoutMInput2 = findViewById(R.id.layoutMInput2);
        editMInput2.setHint(placeHolder);
        layoutMInput2.setVisibility(View.VISIBLE);
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        editMInput2.setText(userInfo.getIntroduce());
    }

    public void saveInfo() {
        int type = (requestCode & 0x0f0) >> 4;
        switch (type) {
            case 1:
                saveMInput1();
                break;
            case 2:
                saveMInput2();
                break;
            default:
                Toast.makeText(this, "Request code 错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveMInput1() {
        String newValue = editMInput1.getText().toString();
        if (newValue.trim().length() == 0) {
            editMInput1.setText("");
            Utils.shakeView(editMInput1);
            return;
        }
        switch (requestCode) {
            case EditSelfInfoActivity.REQUEST_CODE_EDIT_NICK_NAME:
                saveNickName();
                return;
            case EditSelfInfoActivity.REQUEST_CODE_EDIT_JOB:
                if (newValue.length() > 60) {
                    MessageUtils.showToast(getString(R.string.user_attribute_work_limit, 60));
                    return;
                }
                saveInfo("career");
                return;
            case EditSelfInfoActivity.REQUEST_CODE_EDIT_HOBBY:
                if (newValue.length() > maxLength) {
                    MessageUtils.showToast(getString(R.string.user_attribute_work_limit, maxLength));
                    return;
                }
                saveInfo("interests");
                return;
            case CertActivity.REQUEST_CODE_CHANGE_EMAIL:
                saveEmail();
                break;
            default:
                ToastUtil.toast(EditInfoDetailActivity.this, "请求码错误", Toast.LENGTH_SHORT);
                return;
        }
    }

    /**
     * 用于保存career、interests
     **/
    private void saveInfo(String key) {
        showLoading(false);
        String newValue = editMInput1.getText().toString();
        Map<String, String> map = new HashMap<>();
        map.put(key, newValue);
        UserBusiness.updateProfile(apiProxy, map);
    }

    private void saveEmail() {
        final String newValue = editMInput1.getText().toString();
        if (!TextUtils.isEmpty(newValue)) {
            if (newValue.length() > 50) {
                MessageUtils.showToast(getString(R.string.user_attribute_work_limit, 50));
                return;
            }
            if (!Utils.isEmail(newValue)) {
                MessageUtils.showToast(getString(R.string.mail_limit));
                return;
            }
        } else {
            MessageUtils.showToast(getString(R.string.mail_limit));
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(dialogTitle).setMessage(String.format(dialogContent, newValue)).create();
        builder.setPositiveButton(R.string.operation_yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showLoading(false);
                Map<String, String> map = new HashMap<>();
                map.put("email", newValue);
                UserBusiness.updateProfile(apiProxy, map);
            }
        }).setNegativeButton(R.string.operation_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    private void saveNickName() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String newValue = editMInput1.getText().toString();
        if (TextUtils.isEmpty(newValue)) {
            Utils.shakeView(editMInput1);
            return;
        }
        if (newValue.length() > maxLength) {
            Utils.shakeView(editMInput1);
            return;
        }
        builder.setTitle(dialogTitle).setMessage(String.format(dialogContent, newValue)).create();
        builder.setPositiveButton(R.string.operation_yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showLoading(false);
                Map<String, String> map = new HashMap<>();
                map.put("nick", newValue);
                UserBusiness.updateProfile(apiProxy, map);
            }
        }).setNegativeButton(R.string.operation_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }

    private void saveMInput2() {
        showLoading(false);
        String content = editMInput2.getContent().toString();
        Map<String, String> map = new HashMap<>();
        map.put("introduce", content);
        UserBusiness.updateProfile(apiProxy, map);
    }
}
